/******************************************************************************
 *      Mestrado em Ciência da Computação - UFMS
 *		Redes de Computadores - Prof. Dr. Ronaldo Alves Ferreira
 *		Alunos: Geraldo Landre, Marcel Tolentino, Vinícius Bueno
 *****************************************************************************/
/* tcplisten.c - tcplisten */

#include "tcpfms.h"
#include "tcp.h"
#include "tcb.h"

/*------------------------------------------------------------------------
 *  tcplisten -  do LISTEN state processing
 *------------------------------------------------------------------------
 */

//Verificar
int tcplisten(struct tcb *ptcb, struct udp *pudp)
{
	struct	tcb	*newptcb;
	//struct	ip	*pip = (struct ip *)pep->ep_data;
	struct	tcp	*ptcp = (struct tcp*)(pudp->udp_data);

	if (ptcp->tcp_code & TCPF_RST)
		return OK;		/* "parent" TCB still in LISTEN */
	if ((ptcp->tcp_code & TCPF_ACK) ||
	    (ptcp->tcp_code & TCPF_SYN) == 0)
		return tcpreset(pudp);
	newptcb = tcballoc();
	if ((int)newptcb == SYSERR || tcpsync(newptcb) == SYSERR )
		return SYSERR;
	newptcb->tcb_state = TCPS_SYNRCVD;
	newptcb->tcb_ostate = TCPO_IDLE;
	newptcb->tcb_error = 0;
	newptcb->tcb_pptcb = ptcb;			/* for ACCEPT	*/

	newptcb->tcb_rip = pudp->ip_src;
	newptcb->tcb_rport = ptcp->tcp_sport;
	newptcb->tcb_lip = pudp->ip_dst;
	newptcb->tcb_lport = ptcp->tcp_dport;

	tcpwinit(ptcb, newptcb, pudp);	/* initialize window data	*/

	newptcb->tcb_finseq = newptcb->tcb_pushseq = 0;
	newptcb->tcb_flags = TCBF_NEEDOUT;
	TcpPassiveOpens++;
	tcpdata(newptcb, pudp);
	sem_post(&(newptcb->tcb_mutex));
        printf("[tcplisten]: TCPS_SYNRCVD: %d\n", newptcb->tcb_dvnum);
	return OK;
}
